package top.likeqc.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author likeqc
 * @since 2022-03-14
 */
@Data
@EqualsAndHashCode(callSuper = true)
public class SysUser extends BaseEntity {

    private static final long serialVersionUID = 1L;

    @NotBlank(message = "用户名不能为空")
    private String username;

    private String password;

    private String avatar;

    @NotBlank(message = "邮箱不能为空")
    @Email(message = "邮箱格式不正确")
    private String email;

    private String city;

    private LocalDateTime lastLogin;

    @TableField(exist = false)
    private List<SysRole> sysRoles = new ArrayList<>();

    /**
     * 判断当前用户有教师角色
     * @return
     */
    public boolean hasRoleTeacher() {
        return hasRole("teacher");
    }

    /**
     * 判断当前用户有管理员角色
     * @return
     */
    public boolean hasRoleAdmin() {
        return hasRole("admin");
    }

    /**
     * 判断当前用户有学生角色
     * @return
     */
    public boolean hasRoleStudent() {
        return hasRole("student");
    }

    /**
     * 判断当前用户有指定角色
     * @return
     */
    public boolean hasRole(String roleCode) {

        if (StringUtils.isBlank(roleCode)) {
            return false;
        }

        AtomicBoolean flag = new AtomicBoolean(false);
        sysRoles.forEach(role -> {
            if (roleCode.equals(role.getCode())) {
                flag.set(true);
            }
        });
        return flag.get();
    }
}
